{extend name='main'}

{block name="button"}
<button type="button" class="layui-btn layui-btn-sm" id="btn-refresh-tables">
    <i class="layui-icon">&#xe669;</i> 刷新表列表
</button>
{/block}

{block name="content"}
<div class="layui-row layui-col-space15">
    <!-- 左侧：表列表 -->
    <div class="layui-col-md4">
        <div class="think-box-shadow">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="layui-icon">&#xe857;</i> 数据库表列表
                </div>
                <div class="layui-card-body" style="padding:0;">
                    <div class="layui-form">
                        <div style="padding:15px;">
                            <input type="text" class="layui-input" id="search-table" placeholder="搜索表名...">
                        </div>
                        <div style="max-height:600px; overflow-y:auto;" id="table-list-container">
                            <table class="layui-table" lay-skin="line" style="margin:0;">
                                <tbody id="table-list">
                                    {volist name="tableList" id="table"}
                                    <tr class="table-item" data-table="{$table.name}" style="cursor:pointer;">
                                        <td>
                                            <div class="table-name">
                                                <i class="layui-icon">&#xe857;</i> {$table.name}
                                            </div>
                                            {notempty name="table.comment"}
                                            <div class="table-comment" style="color:#999; font-size:12px; margin-top:5px;">
                                                {$table.comment}
                                            </div>
                                            {/notempty}
                                        </td>
                                    </tr>
                                    {/volist}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 右侧：代码生成配置 -->
    <div class="layui-col-md8">
        <div class="think-box-shadow">
            <form class="layui-form layui-card" id="generator-form">
                <div class="layui-card-body">
                    <fieldset class="layui-elem-field">
                        <legend>表信息</legend>
                        <div class="layui-field-box">
                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label"><i class="layui-icon layui-icon-form" style="color:#1e9fff;"></i> 表名</label>
                                        <div class="layui-input-block">
                                            <input type="text" class="layui-input" readonly id="selected_table_name" placeholder="请从左侧选择表">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label"><i class="layui-icon layui-icon-edit" style="color:#ffb800;"></i> 表注释</label>
                                        <div class="layui-input-block">
                                            <input type="text" class="layui-input" id="table_comment" placeholder="模块名称，如：用户、企业">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </fieldset>

                    <fieldset class="layui-elem-field" id="fields-preview" style="display:none;">
                        <legend><i class="layui-icon layui-icon-template-1" style="color:#16baaa;"></i> 字段配置</legend>
                        <div class="layui-field-box">
                            <div style="margin-bottom:10px; padding:10px; background:#f8f8f8; border-radius:4px;">
                                <span class="color-desc"><i class="layui-icon layui-icon-tips"></i> 可以修改字段的表单类型，以适应不同的业务需求</span>
                            </div>
                            <div style="max-height:400px; overflow-y:auto;" id="fields-container">
                                <table class="layui-table" lay-size="sm" id="fields-table">
                                    <thead>
                                        <tr>
                                            <th width="15%">字段名</th>
                                            <th width="10%">数据类型</th>
                                            <th width="18%">注释</th>
                                            <th width="18%">表单类型</th>
                                            <th width="10%">是否必填</th>
                                            <th width="12%">显示列表</th>
                                            <th width="12%">显示表单</th>
                                        </tr>
                                    </thead>
                                    <tbody id="fields-list">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </fieldset>

                    <fieldset class="layui-elem-field">
                        <legend>生成选项</legend>
                        <div class="layui-field-box">
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <input type="checkbox" name="generate_model" checked title="生成Model" lay-skin="primary">
                                    <input type="checkbox" name="generate_controller" checked title="生成Controller" lay-skin="primary">
                                    <input type="checkbox" name="generate_view" checked title="生成View" lay-skin="primary">
                                </div>
                            </div>
                            <div class="layui-form-item text-center">
                                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="btn-debug-config">
                                    <i class="layui-icon">&#xe60a;</i> 调试字段配置
                                </button>
                            </div>
                        </div>
                    </fieldset>

                    <div class="layui-form-item text-center">
                        <button type="button" class="layui-btn" id="btn-preview" disabled>
                            <i class="layui-icon">&#xe615;</i> 预览代码
                        </button>
                        <button type="button" class="layui-btn layui-btn-normal" id="btn-generate" disabled>
                            <i class="layui-icon">&#xe654;</i> 生成文件
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.table-item {
    transition: background-color 0.3s;
}
.table-item:hover {
    background-color: #f8f8f8;
}
.table-item.active {
    background-color: #e8f4ff;
}
.table-name {
    font-weight: bold;
    color: #333;
}
fieldset {
    margin-bottom: 20px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
}
fieldset legend {
    font-weight: bold;
    color: #333;
    padding: 0 10px;
}
.layui-field-box {
    padding: 15px;
}
#fields-table {
    margin: 0;
    table-layout: fixed; /* 固定表格布局 */
}
#fields-table thead th {
    background: #f8f8f8;
    font-weight: bold;
    color: #333;
    text-align: center; /* 居中对齐 */
}
#fields-table tbody tr:hover {
    background: #f9f9f9;
}
#fields-table td {
    text-align: center; /* 单元格内容居中 */
    vertical-align: middle; /* 垂直居中 */
}
.field-type-select {
    width: 100%;
    height: 32px;
    border: 1px solid #e6e6e6;
    border-radius: 2px;
    padding: 0 10px;
}
.field-required-switch, .field-show-list-switch, .field-show-form-switch {
    display: inline-block;
    transform: scale(0.8); /* 适当缩小复选框 */
}
.custom-modal-container {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.custom-modal-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 0;
    min-height: 0;
}

.custom-modal-tabs {
    border-bottom: 2px solid #e6e6e6;
    background: #fafafa;
    padding: 0 15px;
    display: flex;
    overflow-x: auto;
    scrollbar-width: thin;
    flex-shrink: 0;
}

.custom-modal-tabs::-webkit-scrollbar {
    height: 6px;
}

.custom-modal-tabs::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.custom-modal-tab {
    padding: 12px 20px;
    cursor: pointer;
    border-bottom: 3px solid transparent;
    margin-bottom: -2px;
    white-space: nowrap;
    color: #666;
    transition: all 0.2s;
    position: relative;
    user-select: none;
}

.custom-modal-tab:hover {
    color: #1e9fff;
    background: #f0f9ff;
}

.custom-modal-tab.active {
    color: #1e9fff;
    border-bottom-color: #1e9fff;
    font-weight: bold;
    background: #fff;
}

.custom-modal-tab:not(:last-child)::after {
    content: '';
    position: absolute;
    right: 0;
    top: 25%;
    height: 50%;
    width: 1px;
    background: #ddd;
}

.custom-modal-content {
    flex: 1;
    overflow: hidden;
    padding: 0;
    position: relative;
    background: #f9f9f9;
    min-height: 0;
}

.custom-tab-pane {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    flex-direction: column;
    overflow: hidden;
}

.custom-tab-pane.active {
    display: flex;
}

.file-info {
    padding: 12px 20px;
    background: #e8f4ff;
    border-bottom: 1px solid #d0e6ff;
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.file-info .file-path {
    color: #1e9fff;
    font-weight: 500;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 13px;
}

.code-preview {
    flex: 1;
    padding: 0;
    margin: 0;
    border-radius: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    min-height: 0;
}

.code-preview pre {
    margin: 0;
    padding: 15px;
    flex: 1;
    overflow: auto;
    background: #272822;
    color: #f8f8f2;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.6;
    white-space: pre;
    word-wrap: normal;
}

.code-preview pre code {
    display: block;
    color: #f8f8f2;
}

.code-preview-toolbar {
    padding: 8px 15px;
    background: #f0f0f0;
    border-bottom: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
}

.custom-modal-footer {
    padding: 15px 20px;
    border-top: 2px solid #ffb800;
    background: #fff9e6;
    flex-shrink: 0;
}

.overwrite-compact {
    display: inline-flex;
    align-items: center;
    padding: 8px 15px;
    background: #fff;
    border-radius: 20px;
    border: 2px solid #e6e6e6;
    cursor: pointer;
    transition: all 0.3s;
    margin-right: 12px;
    font-size: 13px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    vertical-align: middle;
}

.overwrite-compact:hover {
    border-color: #1e9fff;
    box-shadow: 0 2px 8px rgba(30,159,255,0.2);
}

.overwrite-compact input[type="radio"] {
    margin: 0 6px 0 0;
    vertical-align: middle;
    position: relative;
    top: 0;
}

.overwrite-compact .option-text {
    display: inline-block;
    vertical-align: middle;
    color: #333;
    line-height: 1;
}

.overwrite-compact .option-text strong {
    font-size: 13px;
    font-weight: 500;
    line-height: 1;
}
</style>

<script>
layui.use(['form', 'layer'], function(){
    const form = layui.form;
    const layer = layui.layer;
    const $ = layui.jquery;
    
    let currentCodes = [];
    let selectedTable = null;
    
    // 表搜索
    $('#search-table').on('input', function(){
        const keyword = $(this).val().toLowerCase();
        $('.table-item').each(function(){
            const tableName = $(this).data('table').toLowerCase();
            const tableComment = $(this).find('.table-comment').text().toLowerCase();
            if (tableName.indexOf(keyword) > -1 || tableComment.indexOf(keyword) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
    
    // 选择表
    $('.table-item').on('click', function(){
        $('.table-item').removeClass('active');
        $(this).addClass('active');
        
        selectedTable = $(this).data('table');
        $('#selected_table_name').val(selectedTable);
        
        // 启用按钮
        $('#btn-preview, #btn-generate').prop('disabled', false);
        
        // 获取字段信息
        loadTableFields(selectedTable);
    });
    
    // 刷新表列表
    $('#btn-refresh-tables').on('click', function(){
        location.reload();
    });
    
    // 调试字段配置
    $('#btn-debug-config').on('click', function(){
        console.log('当前字段配置:', fieldsConfig);
        let configStr = '';
        for (let fieldName in fieldsConfig) {
            const field = fieldsConfig[fieldName];
            configStr += `${fieldName}: 列表显示=${field.show_in_list}, 表单显示=${field.show_in_form}\n`;
        }
        alert('字段配置:\n' + configStr);
    });
    
    // 加载表字段
    function loadTableFields(tableName) {
        layer.load(1);
        
        console.log('=== 开始加载表字段 ===');
        console.log('表名:', tableName);
        
        $.ajax({
            url: '{:url("getTableFields")}',
            type: 'POST',
            data: {table_name: tableName},
            success: function(res) {
                layer.closeAll('loading');
                if (res.code === 1 || parseInt(res.code) === 1) {
                    const tableInfo = res.data;
                    if (tableInfo.fields && tableInfo.fields.length > 0) {
                        // 设置表注释
                        $('#table_comment').val(tableInfo.comment || '');
                        
                        // 显示字段列表
                        showFieldsList(tableInfo.fields);
                        
                        // layer.msg('加载成功，共 ' + tableInfo.fields.length + ' 个字段', {icon: 1});
                    } else {
                        layer.msg('该表没有字段', {icon: 0});
                        console.warn('没有字段数据');
                    }
                } else {
                    const errorMsg = res.msg || res.info || '获取字段信息失败';
                    layer.msg(errorMsg, {time: 5000, icon: 2});
                    console.error('=== 错误信息 ===');
                    console.error('错误:', errorMsg);
                    console.error('完整响应:', res);
                }
            },
            error: function(xhr, status, error) {
                layer.closeAll('loading');
                console.error('=== AJAX错误 ===');
                console.error('status:', status);
                console.error('error:', error);
                console.error('xhr:', xhr);
                console.error('responseText:', xhr.responseText);
                layer.msg('网络错误: ' + error, {icon: 2, time: 5000});
            }
        });
    }
    
    // 存储字段配置
    let fieldsConfig = {};
    
    // 显示字段列表
    function showFieldsList(fields) {
        console.log('=== 开始显示字段列表 ===');
        console.log('字段数据:', fields);
        console.log('字段数量:', fields.length);
        
        if (!fields || fields.length === 0) {
            console.warn('没有字段数据');
            layer.msg('没有可显示的字段', {icon: 0});
            return;
        }
        
        let html = '';
        
        // 表单类型选项
        const formTypes = [
            {value: 'text', label: '文本框'},
            {value: 'number', label: '数字输入'},
            {value: 'textarea', label: '文本域'},
            {value: 'radio', label: '单选按钮'},
            {value: 'checkbox', label: '多选框'},
            {value: 'select', label: '下拉选择'},
            {value: 'date', label: '日期选择'},
            {value: 'datetime', label: '日期时间'},
            {value: 'image', label: '图片上传'},
            {value: 'images', label: '多图上传'},
            {value: 'images_sortable', label: '可排序多图上传'},
            {value: 'file', label: '文件上传'},
            {value: 'editor', label: '富文本编辑器'},
            {value: 'password', label: '密码输入'},
            {value: 'switch', label: '开关'},
            {value: 'color', label: '颜色选择'},
        ];
        
        // 清空之前的配置
        fieldsConfig = {};
        
        fields.forEach(function(field, index) {
            console.log(`处理字段 ${index + 1}:`, field);
            
            // 保存字段配置
            fieldsConfig[field.name] = {
                name: field.name,
                type: field.type,
                length: field.length,
                comment: field.comment || '',
                required: field.required || false,
                form_type: field.form_type || 'text',
                show_in_list: field.show_in_list !== undefined ? field.show_in_list : true,  // 默认在列表显示
                show_in_form: field.show_in_form !== undefined ? field.show_in_form : true   // 默认在表单显示
            };
            
            // 生成表单类型下拉框
            let selectOptions = '';
            formTypes.forEach(function(type) {
                const selected = type.value === field.form_type ? 'selected' : '';
                selectOptions += `<option value="${type.value}" ${selected}>${type.label}</option>`;
            });
            
            html += `
                <tr data-field="${field.name}">
                    <td>
                        <strong>${field.name}</strong>
                    </td>
                    <td>
                        <span class="layui-badge layui-bg-gray">${field.type}${field.length ? '(' + field.length + ')' : ''}</span>
                    </td>
                    <td>
                        <input type="text" class="layui-input layui-input-sm field-comment" 
                               data-field="${field.name}" 
                               value="${field.comment || ''}" 
                               placeholder="请输入字段注释">
                    </td>
                    <td>
                        <select class="field-type-select"  lay-filter="field-type-select"  data-field="${field.name}">
                            ${selectOptions}
                        </select>
                    </td>
                    <td class="text-center">
                        <input type="checkbox" class="field-required-checkbox" 
                               data-field="${field.name}" 
                               ${field.required ? 'checked' : ''} 
                               lay-skin="switch" 
                               lay-filter="field-required"
                               lay-text="是|否">
                    </td>
                    <td class="text-center">
                        <input type="checkbox" class="field-show-list-checkbox" 
                               data-field="${field.name}" 
                               ${field.show_in_list !== false ? 'checked' : ''} 
                               lay-skin="switch" 
                               lay-filter="field-show-list"
                               lay-text="是|否">
                    </td>
                    <td class="text-center">
                        <input type="checkbox" class="field-show-form-checkbox" 
                               data-field="${field.name}" 
                               ${field.show_in_form !== false ? 'checked' : ''} 
                               lay-skin="switch" 
                               lay-filter="field-show-form"
                               lay-text="是|否">
                    </td>
                </tr>
            `;
        });
        $('#fields-list').html(html);
        $('#fields-preview').show();
        // 重新渲染表单
        form.render();
        // 调试：输出所有字段配置
        console.log('所有字段配置:', fieldsConfig);
        // 绑定字段类型变更事件
        form.on('select(field-type-select)', function(data){
            const fieldName = $(data.elem).data('field');
            console.log(`字段 ${fieldName} 的表单类型变更为: ${data.value}`);
            // const elem = data.elem; // 获得 select 原始 DOM 对象
            const value = data.value; // 获得被选中的值
            // const othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象
            if (fieldsConfig[fieldName]) {
                fieldsConfig[fieldName].form_type = value;
            }
        });
        // 绑定注释变更事件
        $('.field-comment').on('input', function() {
            const fieldName = $(this).data('field');
            const comment = $(this).val();
            if (fieldsConfig[fieldName]) {
                fieldsConfig[fieldName].comment = comment;
            }
        });
        // 绑定必填开关事件
        form.on('switch(field-required)', function(data){
            const fieldName = $(data.elem).data('field');
            const required = data.elem.checked;
            console.log(`字段 ${fieldName} 的必填状态变更为: ${required}`);
            if (fieldsConfig[fieldName]) {
                fieldsConfig[fieldName].required = required;
            }
        });
        
        // 绑定列表显示开关事件
        form.on('switch(field-show-list)', function(data){
            const fieldName = $(data.elem).data('field');
            const showInList = data.elem.checked;
            console.log(`字段 ${fieldName} 的列表显示状态变更为: ${showInList}`);
            if (fieldsConfig[fieldName]) {
                fieldsConfig[fieldName].show_in_list = showInList;
                // 更新字段配置对象
                fieldsConfig[fieldName] = Object.assign({}, fieldsConfig[fieldName], {show_in_list: showInList});
            }
        });
        
        // 绑定表单显示开关事件
        form.on('switch(field-show-form)', function(data){
            const fieldName = $(data.elem).data('field');
            const showInForm = data.elem.checked;
            if (fieldsConfig[fieldName]) {
                fieldsConfig[fieldName].show_in_form = showInForm;
                // 更新字段配置对象
                fieldsConfig[fieldName] = Object.assign({}, fieldsConfig[fieldName], {show_in_form: showInForm});
            }
        });
    }
    
    // 预览代码
    $('#btn-preview').on('click', function(){
        if (!selectedTable) {
            layer.msg('请先选择表');
            return false;
        }
        
        const formData = getFormData();
        
        if (!validateForm(formData)) {
            return false;
        }
        
        layer.load(1);
        
        $.ajax({
            url: '{:url("preview")}',
            type: 'POST',
            data: formData,
            success: function(res) {
                layer.closeAll('loading');
                
                if (parseInt(res.code) === 1) {
                    currentCodes = res.data;
                    showCodePreview(res.data);
                } else {
                    layer.msg(res.msg || '预览失败');
                }
            },
            error: function() {
                layer.closeAll('loading');
                layer.msg('网络错误');
            }
        });
    });
    
    // 生成文件
    $('#btn-generate').on('click', function(){
        if (!selectedTable) {
            layer.msg('请先选择表');
            return false;
        }
        
        const formData = getFormData();
        
        if (!validateForm(formData)) {
            return false;
        }
        
        layer.load(1);
        
        $.ajax({
            url: '{:url("preview")}',
            type: 'POST',
            data: formData,
            success: function(res) {
                layer.closeAll('loading');
                
                if (res.code === 1) {
                    currentCodes = res.data;
                    showCodePreview(res.data);
                } else {
                    layer.msg(res.msg || '预览失败');
                }
            },
            error: function() {
                layer.closeAll('loading');
                layer.msg('网络错误');
            }
        });
    });
    
    // 显示代码预览（使用Layui弹框）
    function showCodePreview(codes) {
        let tabsHeader = '';
        let tabsContent = '';
        
        codes.forEach(function(item, index) {
            const active = index === 0 ? 'active' : '';
            
            // 根据文件类型确定语言
            let language = 'markup'; // 默认HTML
            if (item.type === 'controller' || item.type === 'model') {
                language = 'php';
            } else if (item.type === 'view') {
                language = 'markup';
            }
            
            tabsHeader += `<div class="custom-modal-tab ${active}" data-index="${index}">${item.name}</div>`;
            
            tabsContent += `
                <div class="custom-tab-pane ${active}" data-index="${index}">
                    <div class="file-info">
                        <div>文件类型: <span class="color-blue">${item.type}</span></div>
                        <div class="file-path">${item.path}</div>
                    </div>
                    <div class="code-preview">
                        <div class="code-preview-toolbar">
                            <div style="font-size:12px; color:#666;">代码预览</div>
                            <button class="copy-code-btn layui-btn layui-btn-primary layui-btn-sm" data-index="${index}">
                                <i class="layui-icon layui-icon-copy"></i> 复制代码
                            </button>
                        </div>
                        <pre><code class="language-${language}">${escapeHtml(item.content)}</code></pre>
                    </div>
                </div>
            `;
        });
        
        // 使用Layui弹框
        const previewIndex = layer.open({
            type: 1,
            title: '<i class="layui-icon layui-icon-file"></i> 代码预览',
            area: ['85%', '80%'],
            offset: ['100px', '220px'],
            shade: 0.3,
            shadeClose: true,
            maxmin: true,
            content: `
                <div class="custom-modal-container">
                    <div class="custom-modal-body">
                        <div class="custom-modal-tabs">${tabsHeader}</div>
                        <div class="custom-modal-content">${tabsContent}</div>
                    </div>
                    <div class="custom-modal-footer">
                        <div style="margin-bottom:12px;">
                            <i class="layui-icon layui-icon-tips" style="color:#ffb800; font-size:16px;"></i>
                            <span style="font-size:14px; font-weight:bold; color:#333; margin-left:5px;">覆盖模式：</span>
                            
                            <label class="overwrite-compact">
                                <input type="radio" name="overwrite_layui" value="skip" checked>
                                <span class="option-text"><strong>跳过</strong></span>
                            </label>
                            
                            <label class="overwrite-compact">
                                <input type="radio" name="overwrite_layui" value="backup">
                                <span class="option-text"><strong>备份</strong></span>
                            </label>
                            
                            <label class="overwrite-compact">
                                <input type="radio" name="overwrite_layui" value="overwrite">
                                <span class="option-text"><strong style="color:#ff5722;">覆盖</strong></span>
                            </label>
                        </div>
                        <div style="text-align:center;">
                            <button type="button" class="layui-btn layui-btn-normal" id="btn-layui-confirm-generate">
                                <i class="layui-icon layui-icon-ok"></i> 确认生成
                            </button>
                            <button type="button" class="layui-btn layui-btn-primary" id="btn-layui-cancel">
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            `,
            success: function(layero, index) {
                const $layero = $(layero);
                
                // 应用语法高亮
                // $layero.find('pre code').each(function(i, block) {
                //     highlightCode(block);
                // });
                
                // 标签切换事件 - 直接绑定到每个标签
                $layero.find('.custom-modal-tab').on('click', function(){
                    const tabIndex = $(this).data('index');
                    
                    // 移除所有active类
                    $layero.find('.custom-modal-tab').removeClass('active');
                    $layero.find('.custom-tab-pane').removeClass('active');
                    
                    // 添加active类到当前标签和对应内容
                    $(this).addClass('active');
                    $layero.find(`.custom-tab-pane[data-index="${tabIndex}"]`).addClass('active');
                });
                
                // 复制代码功能
                $layero.find('.copy-code-btn').on('click', function(){
                    const tabIndex = $(this).data('index');
                    const codeContent = codes[tabIndex].content;
                    
                    // 使用现代剪贴板API
                    if (navigator.clipboard && window.isSecureContext) {
                        navigator.clipboard.writeText(codeContent).then(function() {
                            layer.msg('代码复制成功', {icon: 1});
                        }).catch(function() {
                            fallbackCopy(codeContent);
                        });
                    } else {
                        fallbackCopy(codeContent);
                    }
                });
                
                // 备用复制方法
                function fallbackCopy(text) {
                    const textarea = $('<textarea>');
                    textarea.val(text);
                    textarea.css({
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        width: '1px',
                        height: '1px',
                        opacity: 0
                    });
                    $('body').append(textarea);
                    textarea[0].select();
                    
                    try {
                        const successful = document.execCommand('copy');
                        if (successful) {
                            layer.msg('代码复制成功', {icon: 1});
                        } else {
                            layer.msg('复制失败', {icon: 2});
                        }
                    } catch (err) {
                        layer.msg('浏览器不支持复制功能', {icon: 2});
                    }
                    
                    textarea.remove();
                }
                
                // 确认生成按钮事件
                $layero.find('#btn-layui-confirm-generate').on('click', function(){
                    const overwrite = $layero.find('input[name="overwrite_layui"]:checked').val();
                    
                    layer.confirm('确定要生成这些文件吗？', {
                        icon: 3,
                        title: '确认生成'
                    }, function(confirmIndex){
                        layer.close(confirmIndex);
                        layer.load(1);
                        
                        $.ajax({
                            url: '{:url("generate")}',
                            type: 'POST',
                            data: {
                                codes: codes,
                                overwrite: overwrite
                            },
                            success: function(res) {
                                layer.closeAll('loading');
                                
                                if (res.code === 1) {
                                    layer.close(previewIndex);
                                    showGenerateResult(res.data);
                                } else {
                                    layer.msg(res.msg || '生成失败', {icon: 2});
                                }
                            },
                            error: function() {
                                layer.closeAll('loading');
                                layer.msg('网络错误', {icon: 2});
                            }
                        });
                    });
                });
                
                // 取消按钮事件
                $layero.find('#btn-layui-cancel').on('click', function(){
                    layer.close(previewIndex);
                });
            }
        });
    }
    
    // 显示生成结果
    function showGenerateResult(results) {
        let html = '<div style="padding:20px;">';
        html += '<div style="text-align:center; margin-bottom:20px;">';
        html += '<i class="layui-icon layui-icon-ok-circle" style="font-size:48px; color:#16baaa;"></i>';
        html += '<h3 style="margin-top:10px; color:#333;">文件生成完成</h3>';
        html += '</div>';
        
        html += '<table class="layui-table" lay-skin="line">';
        html += '<thead><tr><th width="45%">文件路径</th><th width="20%">状态</th><th width="35%">说明</th></tr></thead>';
        html += '<tbody>';
        
        results.forEach(function(item) {
            let statusHtml = '';
            let statusIcon = '';
            
            if (item.status === 'success') {
                statusIcon = '<i class="layui-icon layui-icon-ok-circle" style="color:#16baaa;"></i>';
                statusHtml = '<span style="color:#16baaa; font-weight:bold;">生成成功</span>';
            } else if (item.status === 'backup') {
                statusIcon = '<i class="layui-icon layui-icon-ok-circle" style="color:#ffb800;"></i>';
                statusHtml = '<span style="color:#ffb800; font-weight:bold;">已备份</span>';
            } else if (item.status === 'skip') {
                statusIcon = '<i class="layui-icon layui-icon-help" style="color:#999;"></i>';
                statusHtml = '<span style="color:#999;">已跳过</span>';
            } else {
                statusIcon = '<i class="layui-icon layui-icon-close-fill" style="color:#ff5722;"></i>';
                statusHtml = '<span style="color:#ff5722; font-weight:bold;">失败</span>';
            }
            
            html += `
                <tr>
                    <td><code style="background:#f5f5f5; padding:2px 8px; border-radius:2px;">${item.file}</code></td>
                    <td>${statusIcon} ${statusHtml}</td>
                    <td>${item.message}</td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        html += '<div class="text-center" style="margin-top:20px;">';
        html += '<button type="button" class="layui-btn layui-btn-normal" onclick="location.reload()"><i class="layui-icon layui-icon-ok"></i> 完成</button>';
        html += '</div>';
        html += '</div>';
        
        layer.open({
            type: 1,
            title: '<i class="layui-icon layui-icon-ok-circle" style="color:#16baaa;"></i> 生成完成',
            area: ['800px', '600px'],
            offset: ['10%', 'auto'],
            shade: 0,
            shadeClose: false,
            content: html
        });
    }
    
    // 获取表单数据
    function getFormData() {
        // 收集字段配置
        const fields = [];
        for (let fieldName in fieldsConfig) {
            fields.push(fieldsConfig[fieldName]);
        }
        
        return {
            table_name: selectedTable,
            module_name: $('#table_comment').val(),
            fields_config: fields, // 字段配置
            generate_model: $('input[name="generate_model"]').is(':checked') ? 1 : 0,
            generate_controller: $('input[name="generate_controller"]').is(':checked') ? 1 : 0,
            generate_view: $('input[name="generate_view"]').is(':checked') ? 1 : 0
        };
    }
    
    // 验证表单
    function validateForm(data) {
        if (!data.table_name) {
            layer.msg('请选择表');
            return false;
        }
        if (!data.generate_model && !data.generate_controller && !data.generate_view) {
            layer.msg('请至少选择一个生成选项');
            return false;
        }
        return true;
    }
    
    // HTML转义
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function (m) {
            return map[m];
        });
    }
    
    // 简单的语法高亮函数
    function highlightCode(block) {
        const code = $(block).text();
        const language = $(block).attr('class').match(/language-(\w+)/);
        if (!language) return;
        
        let highlighted = code;
        
        if (language[1] === 'php') {
            // PHP语法高亮
            highlighted = highlighted
                // 注释  \' aaa dd \''
                // .replace(/(\/\/.*$)/gm, '<span style="color:#75715e;">$1</span>')
                // .replace(/(\/\*[\s\S]*?\*\/)/g, '<span style="color:#75715e;">$1</span>')
                // 字符串 (改进正则表达式，避免匹配HTML标签中的颜色值)
                // .replace(/'((?:[^"\\]|\\.)*?)'/g, '<span style="color:#e6db74;">"$1"</span>')
                // .replace(/"((?:[^"\\]|\\.)*?)"/g, '<span style="color:#e6db74;">"$1"</span>')
                // 关键字
                .replace(/\b(namespace|use|class|extends|public|protected|private|function|return|if|else|foreach|as|new|static|const|array|true|false|null|try|catch|throw|switch|case|default|break|continue|while|for|do|echo|print|require|include|isset|empty|declare|strict_types)\b/g, '<span style="color:#f92672;">$1</span>')
                // 变量
                .replace(/(\$\w+)/g, '<span style="color:#fd971f;">$1</span>')
                // 数字
                .replace(/\b(\d+)\b/g, '<span style="color:#ae81ff;">$1</span>')
                // PHP标签
                .replace(/(&lt;\?php|&lt;\?|\?&gt;)/g, '<span style="color:#f92672;">$1</span>')
                // 类名和命名空间
                .replace(/\b([A-Z]\w+)(?=\s|;|::|\\)/g, '<span style="color:#66d9ef;">$1</span>');
        } else if (language[1] === 'markup') {
            // HTML语法高亮
            // highlighted = highlighted
                // 注释
                // .replace(/(&lt;!--[\s\S]*?--&gt;)/g, '<span style="color:#75715e;">$1</span>')
                // 标签
                // .replace(/(&lt;\/?[\w-]+)/g, '<span style="color:#f92672;">$1</span>')
                // .replace(/(\/?&gt;)/g, '<span style="color:#f92672;">$1</span>')
                // 属性名
                // .replace(/\s([\w-]+)=/g, ' <span style="color:#a6e22e;">$1</span>=')
                // 属性值
                // .replace(/=(&quot;[^&]*&quot;|&#039;[^&]*&#039;)/g, '=<span style="color:#e6db74;">$1</span>')
                // ThinkPHP模板标签
                // .replace(/(\{[\s\S]*?\})/g, '<span style="color:#66d9ef;">$1</span>')
                // 变量
                // .replace(/(\$\w+)/g, '<span style="color:#fd971f;">$1</span>');
        }
        
        $(block).html(highlighted);
    }
    
    form.render();
});
</script>

{/block}